package com.st.controller;

import com.st.lock.util.RedisLock;
import com.st.service.TestService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.HashMap;
import java.util.Map;
import java.util.Random;
import java.util.UUID;

@Controller
public class TestController {
    @Autowired
    private RedisLock redisLock;

    @Autowired
    private TestService testService;

    @RequestMapping("/test")
    @ResponseBody
    public Map test(){
        Map result = new HashMap();
        long num = 0;
        int time = 10;
        String requestId = UUID.randomUUID().toString().replace("-","")+(new Random().nextInt(9000)+1000);
        //嘗試獲取鎖
        redisLock.tryGetLock(requestId,time);
        //启动子线程续命
        Thread t1 = redisLock.createLifeThread(time,requestId);
        try {
            t1.setDaemon(true);//守护线程
            t1.start();//启动续命线程
            result.put("num",testService.updateNum());
            result.put("tid:",requestId);
        } finally {
            //停止续命线程
            t1.interrupt();
            //释放锁
            redisLock.releaseLock(requestId);
        }
        return result;
    }


//    @RequestMapping("/test")
//    @ResponseBody
//    public Map test(){
//        Map result = new HashMap();
//        result.put("num",testService.updateNum());
//        return result;
//    }

}
